<template>
	<div class="div-user-sum">
		<div class="div-top">
			<span>学生管理</span>
		</div>
		<span class="search_label">学号:</span>
		<el-input placeholder="请输入学号" prefix-icon="el-icon-search" v-model="studentNo" style="width:207px;margin-left: 10px" clearable/>
		<span class="search_label">姓名:</span>
		<el-input placeholder="请输入姓名" prefix-icon="el-icon-search" v-model="studentName" style="width:207px;margin-left: 10px" clearable/>
		<span class="search_label">性别:</span>
		<el-select v-model="sex" placeholder="请选择性别" style="width:207px" clearable>
			<el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value">
			</el-option>
		</el-select>
		<span class="search_label">所在班级:</span>
		<el-cascader v-model="organizationIds" :options="organizations" @change='searchOrgChange' placeholder="请选择班级" style="width:207px;" :props='classProps' :show-all-levels='false' clearable></el-cascader>
		<el-button type="primary" @click="search" style="margin-left: 5px">搜索</el-button>
		<el-button type="primary" @click="teacherSaveDialog=true" icon="el-icon-circle-plus-outline">添加用户</el-button>
		<el-button type="success" @click="dialogImport=true" icon="el-icon-upload2">导入用户</el-button>
		<el-button type="success" @click="exportUser" icon="el-icon-download">{{multipleSelect&& multipleSelect.length>0?'导出所选（'+multipleSelect.length+'）':'导出用户'}}</el-button>
		<div style="margin: 10px;">
			<el-table :data="users" border row-key='studentId'>
				<el-table-column prop="studentNo" label="学号" align="center">
				</el-table-column>
				<el-table-column prop="studentName" label="姓名" align="center">
				</el-table-column>
				<el-table-column prop="sex" label="性别" align="center">
					<template slot-scope="scope">
						<span v-if="scope.row.sex == 'F'">女</span>
						<span v-if="scope.row.sex == 'M'">男</span>
					</template>
				</el-table-column>
				<el-table-column prop="organizationName" label="所在班级" align="center">
				</el-table-column>
				<el-table-column prop="majorName" label="所属专业" align="center">
				</el-table-column>
				<el-table-column label="操作" align="center" width='350'>
					<template slot-scope="scope">
						<el-button type="primary" @click="openEdit(scope.row)" size="small">编辑</el-button>
						<el-button type="danger" @click="openDelete(scope.row.studentId)" size="small">删除</el-button>
						<el-button type="primary" @click="setPassword(scope.row.studentId)" size="small">重置密码</el-button>
					</template>
				</el-table-column>
			</el-table>
			<div style="margin: 10px; text-align: center;">
				<el-pagination background @current-change="currentChange" @size-change='sizeChange' :current-page="pageNum" :page-sizes="[10, 30, 50, 100, 300]" :page-size="pageSize" layout="total, sizes, prev, pager, next, jumper" :total="total">
				</el-pagination>
			</div>
		</div>
		<!-- 添加用户 -->
		<el-dialog title="添加用户" :close-on-press-escape='false' :close-on-click-modal='false' :append-to-body='true' :visible.sync="teacherSaveDialog" width="720px">
			<el-form :model="addForm" :rules="rules" ref="addForm" :inline="true" style='width: calc(100% - 20px);'>
				<el-row>
					<el-col :span='12'>
						<el-form-item label="学号" prop="studentNo" label-width="110px">
							<el-input placeholder="请输入学号" v-model="addForm.studentNo" maxlength="50" style="width:207px;" clearable></el-input>
						</el-form-item>
					</el-col>
					<el-col :span='12'>
						<el-form-item label="真实姓名" prop="studentName" label-width="110px">
							<el-input placeholder="请输入姓名" v-model="addForm.studentName" maxlength="20" style="width:207px;" clearable></el-input>
						</el-form-item>
					</el-col>
					<el-col :span='12'>
						<el-form-item label="性别" prop="sex" label-width="110px">
							<el-select v-model="addForm.sex" placeholder="请选择性别" style="width:207px">
								<el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value">
								</el-option>
							</el-select>
						</el-form-item>
					</el-col>
					<el-col :span='12'>
						<el-form-item label="电话" prop="mobile" label-width="110px">
							<el-input placeholder="请输入电话号码" v-model="addForm.mobile" style="width:207px;" clearable></el-input>
						</el-form-item>
					</el-col>
					<el-col :span='12'>
						<el-form-item label="密码" prop="password" label-width="110px">
							<el-input placeholder="请输入密码" v-model="addForm.password" maxlength="255" style="width:207px;" type='password' clearable></el-input>
						</el-form-item>
					</el-col>
					<el-col :span='12'>
						<el-form-item label="确认密码" prop="passwordcheck" label-width="110px">
							<el-input placeholder="请确认密码" v-model="addForm.passwordcheck" maxlength="255" style="width:207px;" type='password' clearable></el-input>
						</el-form-item>
					</el-col>
					<el-col :span='12'>
						<el-form-item label="所在班级" prop="organizationId" label-width="110px">
							<el-cascader v-model="addForm.organizationIds" :options="organizations" @change='addOrgChange' placeholder="请选择班级" style="width:207px;" :props='classProps' :show-all-levels='false' clearable></el-cascader>
						</el-form-item>
					</el-col>
					<el-col :span='12'>
						<el-form-item label="所属专业" prop="majorId" label-width="110px">
							<el-select v-model="addForm.majorId" placeholder="请选择所属专业" style="width:207px;">
								<el-option v-for="item in majors" :key="item.id" :label="item.name" :value="item.id">
								</el-option>
							</el-select>
						</el-form-item>
					</el-col>
					<!--<el-col :span='12'>
						<el-form-item label="头像" prop="icon" label-width="110px">
							<div class="avataruploads">
								<div class="avatarupcover avatarupcover-add" @click="$refs.icon_add.click()">
									<i class="el-icon-plus"></i>
								</div>
								<img :src="baseurl + addForm.icon" v-if="addForm.icon" />
								<input ref="icon_add" type="file" accept=".jpg, .png, .JPG, .PNG" style="display: none" @change="iconAdd($event)" />
							</div>
						</el-form-item>
					</el-col>-->
				</el-row>
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button @click="resetAdd">取 消</el-button>
				<el-button type="primary" @click="addStudent" :disabled='dataloading'>确 定</el-button>
			</div>
		</el-dialog>
		<!-- 编辑用户 -->
		<el-dialog title="编辑用户" :close-on-press-escape='false' :close-on-click-modal='false' :append-to-body='true' :visible.sync="editUserDialog" width="720px">
			<el-form :model="editForm" :rules="rules" ref="editForm" :inline="true" style='width: calc(100% - 20px);'>
				<el-row>
					<el-col :span='12'>
						<el-form-item label="学号" prop="studentNo" label-width="110px">
							<el-input placeholder="请输入学号" v-model="editForm.studentNo" maxlength="50" style="width:207px;" :disabled="true"></el-input>
						</el-form-item>
					</el-col>
					<el-col :span='12'>
						<el-form-item label="真实姓名" prop="studentName" label-width="110px">
							<el-input placeholder="请输入姓名" v-model="editForm.studentName" maxlength="20" style="width:207px;" clearable></el-input>
						</el-form-item>
					</el-col>
					<el-col :span='12'>
						<el-form-item label="性别" prop="sex" label-width="110px">
							<el-select v-model="editForm.sex" placeholder="请选择性别" style="width:207px">
								<el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value">
								</el-option>
							</el-select>
						</el-form-item>
					</el-col>
					<el-col :span='12'>
						<el-form-item label="电话" prop="mobile" label-width="110px">
							<el-input placeholder="请输入电话号码" v-model="editForm.mobile" style="width:207px;" clearable @input='mobileChanged = true'></el-input>
						</el-form-item>
					</el-col>
					<el-col :span='12'>
						<el-form-item label="所在班级" prop="organizationId" label-width="110px">
							<el-cascader v-model="editForm.organizationIds" :options="organizations" @change='editOrgChange' placeholder="请选择班级" style="width:207px;" :props='classProps' :show-all-levels='false' clearable></el-cascader>
						</el-form-item>
					</el-col>
					<el-col :span='12'>
						<el-form-item label="所属专业" prop="majorId" label-width="110px">
							<el-select v-model="editForm.majorId" placeholder="请选择所属专业" style="width:207px;">
								<el-option v-for="item in majors" :key="item.id" :label="item.name" :value="item.id">
								</el-option>
							</el-select>
						</el-form-item>
					</el-col>
					<!--<el-col :span='12'>
						<el-form-item label="头像" prop="icon" label-width="110px">
							<div class="avataruploads">
								<div class="avatarupcover avatarupcover-add" @click="$refs.icon_edit.click()">
									<i class="el-icon-plus"></i>
								</div>
								<img :src="baseurl + editForm.icon" v-if="editForm.icon" />
								<input ref="icon_edit" type="file" accept=".jpg, .png, .JPG, .PNG" style="display: none" @change="iconEdit($event)" />
							</div>
						</el-form-item>
					</el-col>-->
				</el-row>
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button @click="resetEdit">取 消</el-button>
				<el-button type="primary" @click="editUser">确 定</el-button>
			</div>
		</el-dialog>
		<!-- 导入用户 -->
		<el-dialog title="导入" :close-on-press-escape='false' :close-on-click-modal='false' :append-to-body='true' :visible.sync="dialogImport" width="720px">
			<el-form :model="importUserForm" :rules="importUserRules" ref="importUserValidate" :inline="true">
				<el-form-item label="所在班级" prop="organizationId" label-width="110px">
					<el-cascader v-model="importUserForm.organizationIds" :options="organizations" @change='importOrgChange' placeholder="请选择班级" style="width:207px;" :props='classProps' collapse-tags clearable></el-cascader>
				</el-form-item>
				<el-form-item label="所属专业" prop="majorId" label-width="110px">
					<el-select v-model="importUserForm.majorId" placeholder="请选择所属专业" style="width:207px;">
						<el-option v-for="item in majors" :key="item.id" :label="item.name" :value="item.id">
						</el-option>
					</el-select>
				</el-form-item>
				<el-form-item label="文件" prop="file" label-width="110px">
					<div style="height:80px">
						<p style="margin:auto 0;text-align:center">请下载模板，并严格按照模板格式整理数据后上传；只能上传xls/xlsx格式文件</p>
						<p style="margin:auto 0;text-align:center;color:red">*注意：请勿重复导入相同数据</p>
					</div>
					<el-upload style="text-align:center" ref="upload" action="" :limit="1" :on-change="fileChange" :before-remove="fileRemove" accept=".xls, .xlsx" :auto-upload="false">
						<el-button slot="trigger" size="small" type="primary">选取文件</el-button>
						<el-button style="margin:0 0 0 20px;" size="small" plain @click='downloadTemplate'>下载模板</el-button>
					</el-upload>
				</el-form-item>
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button @click="resetImport">取 消</el-button>
				<el-button type="success" @click="submitUpload">导入</el-button>
			</div>
		</el-dialog>
	</div>
</template>

<script>
	import { studentList, addStudent, updateStudent, studentPwdReset, removeStudent, importStudent, studentExport, updateState, downloadTemplate } from '@/api/student.js'
	import { organizationTree } from '@/api/organization.js'
	import { majorList } from '@/api/major.js'
	import { roleList } from '@/api/role.js'
	import { putProgress } from "@/utils/oss.js";
	export default {
		data() {
			var validatorphone = (rule, value, callback) => {
				let reg;
				if(this.mobileChanged) {
					reg = /^(13[0-9]|14[579]|15[0-3,5-9]|16[6]|17[0135678]|18[0-9]|19[89])\d{8}$/;
				} else {
					reg = /^(13[0-9]|14[579]|15[0-3,5-9]|16[6]|17[0135678]|18[0-9]|19[89])(\d{4}|\*{4})\d{4}$/
				}
				if(!value) {
					callback()
				} else {
					if(!reg.test(value)) {
						callback(new Error('请输入正确的手机号码'))
					} else {
						callback()
					}
				}
			};
			var validatePass1 = (rule, value, callback) => {
				if(this.addForm.passwordcheck) {
					if(value !== this.addForm.passwordcheck) {
						callback(new Error('两次输入密码不一致!'));
					} else {
						callback();
					}
				}
			};
			var validatePass2 = (rule, value, callback) => {
				if(this.addForm.password) {
					if(value !== this.addForm.password) {
						callback(new Error('两次输入密码不一致!'));
					} else {
						callback();
					}
				}
			};
			return {
				userinfo: {},
				roles: [],
				organizations: [],
				majors: [],
				users: [],
				pageNum: 1,
				pageSize: 10,
				total: 0,
				studentNo: '',
				studentName: '',
				sex: '',
				organizationId: '',
				organizationIds: [],
				dialogImport: false,
				teacherSaveDialog: false,
				editUserDialog: false,
				dateUserDialog: false,
				multipleSelect: [],
				dataloading: false,
				mobileChanged: false,
				classProps: {
					value: 'id',
					label: 'name',
				},
				options: [{
					value: "M",
					label: '男'
				}, {
					value: "F",
					label: '女'
				}],
				importUserForm: {
					organizationId: '',
					organizationIds: [],
					file: '',
					majorId: '',
				},
				importUserRules: {
					organizationId: [{
						required: true,
						message: '请选择班级'
					}],
					file: [{
						required: true,
						message: '请选择导入文件'
					}],
					majorId: [{
						required: true,
						message: '请选择专业'
					}],
				},
				addForm: {
					icon: '',
					studentNo: '',
					studentName: '',
					mobile: '',
					sex: '',
					password: '',
					passwordcheck: '',
					majorId: '',
					organizationId: '',
					organizationIds: []
				},
				editForm: {
					userId: '',
					icon: '',
					studentNo: '',
					studentName: '',
					mobile: '',
					sex: '',
					password: '',
					passwordcheck: '',
					majorId: '',
					organizationId: '',
					organizationIds: []
				},
				rules: {
					studentNo: [{
						min: 4,
						message: "学号最少是四位！",
						trigger: "blur",
					}, {
						required: true,
						message: '请输入学号',
						trigger: 'blur'
					}],
					studentName: [{
						required: true,
						message: '请输入姓名',
						trigger: 'blur'
					}],
					icon: [{
						required: true,
						message: '请上传头像',
						trigger: 'blur'
					}],
					sex: [{
						required: true,
						message: '请选择性别',
						trigger: 'blur'
					}],
					password: [{
							required: true,
							message: '请输入密码',
							trigger: 'blur'
						},
						{
							validator: validatePass1,
							trigger: 'blur'
						}
					],
					passwordcheck: [{
							required: true,
							message: '请确认密码',
							trigger: 'blur'
						},
						{
							validator: validatePass2,
							trigger: 'blur'
						}
					],
					mobile: [{
							min: 11,
							max: 11,
							message: "请输入11位手机号码",
							trigger: "blur",
						},
						{
							validator: validatorphone,
							message: "请输入正确的手机号码",
							trigger: 'blur'
						}
					],
					organizationId: [{
						required: true,
						message: '请选择班级',
						trigger: 'blur'
					}],
					majorId: [{
						required: true,
						message: '请选择专业',
						trigger: 'blur'
					}],
				},

			}
		},
		created() {
			this.getMajorList();
			this.getDeptList();
			this.getUserList();
		},
		methods: {
			getChildren(arrs) {
				arrs.map(item => {
					if(item.children && item.children.length > 0) {
						this.getChildren(item.children)
					} else {
						item.children = null;
					}
				})
				return arrs
			},
			downloadTemplate() {
				downloadTemplate();
			},
			searchOrgChange() {
				var organizationIdsLen = this.organizationIds.length;
				if(organizationIdsLen > 0) {
					this.organizationId = this.organizationIds[organizationIdsLen - 1]
				} else {
					this.organizationId = ""
				}
			},
			getUserList() {
				var data = {
					pageNum: this.pageNum,
					pageSize: this.pageSize,
					studentName: this.studentName ? this.studentName : null,
					studentNo: this.studentNo ? this.studentNo : null,
					sex: this.sex ? this.sex : null,
					organizationId: this.organizationId ? this.organizationId : null,
				}
				studentList(data).then(async res => {
					this.users = res.data.list;
					this.total = res.data.total;
				});
			},
			getMajorList() {
				majorList({}).then(async res => {
					this.majors = res.data
				})
			},
			getDeptList() {
				organizationTree({}).then(async res => {
					if(res.code == '200') {
						var organizations = this.getChildren(res.data);
						this.organizations = organizations;
					}
				})
			},
			search() {
				this.pageNum = 1;
				this.getUserList()
			},
			currentChange(pageNum) {
				this.pageNum = pageNum;
				this.getUserList()
			},
			sizeChange(pageSize) {
				this.pageNum = 1;
				this.pageSize = pageSize;
				this.getUserList()
			},
			fileChange(file) {
				this.importUserForm.file = file.raw;
			},
			fileRemove(file) {
				this.importUserForm.file = "";
			},
			resetImport() {
				this.dialogImport = false;
				this.$refs.upload.clearFiles();
				this.file = "";
				this.$refs.importUserValidate.clearValidate();
				this.$refs.importUserValidate.resetFields();
			},
			importOrgChange() {
				var organizationIdsLen = this.importUserForm.organizationIds.length;
				if(organizationIdsLen > 0) {
					this.importUserForm.organizationId = this.importUserForm.organizationIds[organizationIdsLen - 1]
				} else {
					this.importUserForm.organizationId = ""
				}
			},
			submitUpload() {
				this.$refs.importUserValidate.validate(valid => {
					if(valid) {
						if(this.importUserForm.file == "") {
							this.$message({
								message: "文件不能为空",
								type: "error"
							});
							return;
						} else {
							const loading = this.$loading({
								lock: true,
								text: "正在导入请稍等···",
								spinner: "el-icon-loading",
								background: "rgba(0, 0, 0, 0.7)"
							});
							var formData = new FormData();
							formData.append("file", this.importUserForm.file);
							formData.append("organizationId", this.importUserForm.organizationId);
							formData.append("majorId", this.importUserForm.majorId)
							importStudent(formData).then(async res => {
								if(res.code == '200') {
									this.$message({
										message: "导入成功!",
										type: "success"
									});
								} else {
									this.$message({
										message: res.message,
										type: "error"
									});
								}
								loading.close();
								this.dialogImport = false;
								this.importUserForm.file = "";
								this.$refs.upload.clearFiles();
								this.$refs.importUserValidate.clearValidate();
								this.$refs.importUserValidate.resetFields();
								this.getUserList();
							});
						}
					}
				});
			},
			exportUser() {
				studentExport({
					studentName: this.studentName ? this.studentName : null,
					studentNo: this.studentNo ? this.studentNo : null,
					sex: this.sex ? this.sex : null,
					organizationId: this.organizationId ? this.organizationId : null,
				})
			},
			iconAdd(event) {
				const files = event.target.files;
				if(!files || files.length <= 0) {
					return;
				}
				const file = files[0];
				const key = `szhjxpt/icon/${this.getUUID()}/${file.name}`;
				putProgress(key, file).then(res => {
					this.addForm.icon = key;
					this.$refs.icon_add.value = '';
				});
			},
			addOrgChange() {
				var organizationIdsLen = this.addForm.organizationIds.length;
				if(organizationIdsLen > 0) {
					this.addForm.organizationId = this.addForm.organizationIds[organizationIdsLen - 1]
				} else {
					this.addForm.organizationId = ""
				}
			},
			addStudent() {
				this.dataloading = true;
				setTimeout(_ => {
					this.dataloading = false;
				}, 1000)
				this.$refs.addForm.validate((valid) => {
					if(valid) {
						var data = Object.assign({}, this.addForm);
						addStudent(data).then(async res => {
							if(res.code == '200') {
								this.$message({
									message: '添加成功',
									type: 'success'
								});
								this.getUserList();
								this.resetAdd();
							} else {
								this.$message({
									message: res.message,
									type: 'error'
								});
							}
						});
					}
				})
			},
			resetAdd() {
				this.addForm.organizationIds = [];
				this.$nextTick(() => {
					this.$refs.addForm.clearValidate();
					this.$refs.addForm.resetFields();
					this.teacherSaveDialog = false;
				})
			},
			openEdit(item) {
				this.editUserDialog = true;
				this.editForm = Object.assign({}, item, {
					organizationIds: item.organizationId
				});
			},
			iconEdit(event) {
				const files = event.target.files;
				if(!files || files.length <= 0) {
					return;
				}
				const file = files[0];
				const key = `szhjxpt/icon/${this.getUUID()}/${file.name}`;
				putProgress(key, file).then(res => {
					this.editForm = Object.assign({}, this.editForm, {
						icon: key
					});
					this.$refs.icon_edit.value = '';
				});
			},
			editOrgChange() {
				var organizationIdsLen = this.editForm.organizationIds.length;
				if(organizationIdsLen > 0) {
					this.editForm.organizationId = this.editForm.organizationIds[organizationIdsLen - 1]
				} else {
					this.editForm.organizationId = ""
				}
			},
			editUser() {
				this.$refs.editForm.validate((valid) => {
					if(valid) {
						var data = Object.assign({}, this.editForm);
						if(!this.mobileChanged) {
							delete data.mobile
						}
						updateStudent(data).then(async res => {
							if(res.code == '200') {
								this.$message({
									message: '编辑成功',
									type: 'success'
								})
								this.getUserList();
								this.resetEdit();
							} else {
								this.$message({
									message: res.message,
									type: 'error'
								})
							}
						})
					}
				})
			},
			resetEdit() {
				this.editForm.organizationIds = [];
				this.$nextTick(() => {
					this.$refs.editForm.resetFields();
					this.$refs.editForm.clearValidate()
					this.mobileChanged = false;
					this.editUserDialog = false;
				})
			},
			openState(item) {
				var message = item.disabled == '1' ? '是否禁用该用户?' : '是否启用该用户?';
				this.$confirm(message, '提示', {
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					type: 'warning'
				}).then(() => {
					updateState({
						studentId: item.studentId,
						state: item.disabled == '1' ? '0' : '1',
					}).then(async res => {
						if(res.code == '200') {
							this.$message({
								message: res.message,
								type: 'success'
							});
							this.getUserList();
						} else {
							this.$message({
								message: res.message,
								type: 'error'
							});
						}
					})
				}).catch(() => {});
			},
			openDelete(studentId) {
				this.$confirm('是否删除该用户?', '提示', {
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					type: 'warning'
				}).then(() => {
					removeStudent({
						studentId: studentId
					}).then(async res => {
						if(res.code == '200') {
							this.$message({
								message: '删除成功',
								type: 'success'
							})
							this.getUserList();
						} else {
							this.$message({
								message: res.message,
								type: 'error'
							})
						}
					})
				}).catch(() => {});
			},
			setPassword(studentId) {
				this.$confirm('是否重置密码?', '提示', {
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					type: 'warning'
				}).then(() => {
					studentPwdReset({
						studentId: studentId,
					}).then(async res => {
						if(res.code == '200') {
							this.$message({
								message: res.message,
								type: 'success'
							})
						} else {
							this.$message({
								message: res.message,
								type: 'error'
							})
						}
					})
				}).catch(() => {});
			},
			getUUID() {
				return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, c => {
					let r = (Math.random() * 16) | 0,
						v = c == "x" ? r : (r & 0x3) | 0x8;
					return v.toString(16);
				});
			},
		}
	}
</script>